// src/pages/PlatForm/views/ItemManageView/ItemManageView.vue
<script setup>
import { ref, onMounted } from 'vue';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { SecondHandItemApi } from '@/api/SecondHandItemApi.js';
import User from "@/utils/User/User.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';

// 商品列表
const items = ref([]);
const loading = ref(false);
const userId = ref(User.getUserId());

// 获取用户发布的二手商品列表
const fetchItems = async () => {
  loading.value = true;
  try {
    if (!userId.value) {
      ElMessage.warning('请先登录');
      return;
    }

    const response = await UserProfileApi.getSecondHandItems(userId.value);
    items.value = Array.isArray(response) ? response : [];

    console.log('获取到的二手商品数据:', items.value);
  } catch (error) {
    console.error('获取二手商品失败:', error);
    ElMessage.error('获取二手商品列表失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知日期';
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'forSale': '在售',
    'sold': '已售出',
    'reserved': '已预订',
    'expired': '已过期',
    'removed': '已下架'
  };
  return statusMap[status] || status;
};

// 获取状态对应的类型
const getStatusType = (status) => {
  const typeMap = {
    'forSale': 'success',
    'sold': 'info',
    'reserved': 'warning',
    'expired': 'danger',
    'removed': 'info'
  };
  return typeMap[status] || '';
};

// 查看商品详情
const viewItemDetail = (item) => {
  console.log('查看商品:', item);
  // 此处可以添加查看商品详情的逻辑，如跳转到详情页
};

// 编辑商品
const editItem = (item) => {
  console.log('编辑商品:', item);
  // 这里可以跳转到编辑页面或打开编辑对话框
};

// 下架商品
const removeItem = (item) => {
  ElMessageBox.confirm(
      `确定要下架商品"${item.title}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      // 调用SecondHandItemApi删除商品
      await SecondHandItemApi.deleteSecondHandItem(item.itemID);
      ElMessage.success('商品已下架');
      // 刷新列表
      fetchItems();
    } catch (error) {
      console.error('下架商品失败:', error);
      ElMessage.error('下架商品失败: ' + error.message);
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 发布新商品
const publishNewItem = () => {
  // 跳转到商品发布页面
  window.location.href = '/platform/upload/secondhand';
};

onMounted(() => {
  fetchItems();
});
</script>

<template>
  <div class="item-manage-container">
    <div class="page-header">
      <h2>二手商品管理</h2>
      <el-button type="primary" @click="publishNewItem">发布新商品</el-button>
    </div>

    <div class="item-list-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>我发布的商品</span>
            <el-button type="primary" plain size="small" @click="fetchItems">刷新</el-button>
          </div>
        </template>

        <el-table
            v-loading="loading"
            :data="items"
            style="width: 100%"
            empty-text="暂无发布的商品"
        >
          <el-table-column prop="itemID" label="商品ID" width="70" />
          <el-table-column prop="title" label="商品名称" width="150" />
          <el-table-column prop="description" label="商品描述" show-overflow-tooltip />
          <el-table-column prop="price" label="价格" width="80">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="creationTime" label="发布时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.creationTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ formatStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                  size="small"
                  type="danger"
                  :icon="Delete"
                  circle
                  @click="removeItem(scope.row)"
                  title="下架商品"
                  :disabled="scope.row.status === 'removed' || scope.row.status === 'sold'"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<style lang="less" scoped>
.item-manage-container {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 22px;
      color: #303133;
    }
  }

  .item-list-container {
    background-color: #fff;
    border-radius: 4px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: bold;
      :deep(.el-button){
        color: white;
      }
    }
  }
}
</style>
